﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Net;
using System.Xml.Linq;
using System.Xml.XPath;

namespace ClassLibrary.ContactRetriever
{
    using WindowsLive;
    using System.Web;

    using System.Xml.Linq;
    using System.IO;
    using System.Net.Mail;

    public class LiveContactRetriever : IContactRetriever
    {
        string _lid = string.Empty, _token = string.Empty;

        public LiveContactRetriever(string lid, string token)
        {
            _lid = lid;
            _token = token;
        }

        #region IContactRetriever Members

        public List<MailAddress> RetrieveContact()
        {
            string uri = "https://livecontacts.services.live.com/@L@" + _lid + "/rest/LiveContacts/Contacts/";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.UserAgent = "Windows Live Data Interactive SDK";
            request.ContentType = "application/xml; charset=utf-8";
            request.Method = "GET";
            request.Headers.Add("Authorization", "DelegatedToken dt=\"" + _token + "\"");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string ct = new StreamReader(response.GetResponseStream()).ReadToEnd();
            XDocument x = XDocument.Parse(ct);

            return ParseContacts(ref x);
        }
        

        #endregion

        List<MailAddress> ParseContacts(ref XDocument restX)
        {
            string name = string.Empty, value = string.Empty;
            List<MailAddress> ret = new List<MailAddress>();
            foreach (XElement c in restX.Root.Elements("Contact"))
            {
                XElement personal = c.XPathSelectElement("Profiles/Personal");
                //name = personal.Element("LastName").Value + " " + personal.Element("FirstName").Value;
                name = personal.Element("DisplayName").Value;
                try
                {
                    XElement email = c.XPathSelectElements("Emails/Email").First();
                    value = email.Element("Address").Value;
                }
                catch{continue;}

                ret.Add(new MailAddress(value, name));
            }

            return ret;
        }

    }
}
